package com.awei.travel.service.impl;

import com.awei.travel.mapper.UserMapper;
import com.awei.travel.pojo.User;
import com.awei.travel.pojo.UserExample;
import com.awei.travel.req.UserVo;
import com.awei.travel.service.UserService;
import com.awei.travel.utils.BeanConv;
import com.awei.travel.utils.EmptyUtil;
import com.awei.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Wenweiwei
 * @date 2021/3/1 S{TIME}
 */
@Service
public class UserServiceImpl implements UserService {

    //注入UserMapper对象
    @Autowired
    private UserMapper userMapper;

    //注入HttpSession对象
    @Autowired
    HttpSession session;

    /**
     * @Description 用户注册
     * @param userVo 网页传递注册数据信息
     * @return 是否注册成功
     */
    @Override
    public Boolean registerUser(UserVo userVo) {
        User user = BeanConv.toBean(userVo, User.class);
        user.setPassword(MD5Coder.md5Encode(user.getPassword()));
        return userMapper.insert(user) > 0;
    }

    /**
     * @Description 用户登录
     * @param userVo 网页传递的user数据
     * @return 数据库是否有该登录信息
     */
    @Override
    public UserVo loginUser(UserVo userVo) {
        //组装sql查询条件
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(userVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(userVo.getPassword()));
        //查询list结果集
        List<User> users = userMapper.selectByExample(example);
        //转换VO
        List<UserVo> list = BeanConv.toBeanList(users, UserVo.class);
        //判断查询结果
        if (list.size() == 1) {
            UserVo userVoResult = list.get(0);
            //存入会话中
            String sessionId = session.getId();
            userVoResult.setSessionId(sessionId);
            session.setAttribute(sessionId, userVoResult);
            return userVoResult;
        }
        return null;
    }

    /**
     * @Description 用户登出
     */
    @Override
    public void loginOutUser() {
        //会话中删除session对象
        session.removeAttribute(session.getId());
    }

    /**
     * @Description 用户登录状态
     * @return 登录结果结果
     */
    @Override
    public Boolean isLogin() {
        Object attribute = session.getAttribute(session.getId());
        return !EmptyUtil.isNullOrEmpty(attribute);
    }
}
